package com.common.test.coderesolver;

import com.common.test.entity.RpcRequest;
import com.common.test.serializer.JSONSerializer;
import com.common.test.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;



public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> clazz;

    private Serializer jsonSerializer;

    public RpcEncoder(Class<RpcRequest> rpcRequestClass, JSONSerializer jsonSerializer) {
        this.jsonSerializer=jsonSerializer;
        this.clazz=rpcRequestClass;
    }



    /*@Override
    protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
        System.out.println("encoder11111111"+ctx+msg+out);
        out.add(jsonSerializer.serialize(msg));

    }*/



    @Override

    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {

        if (clazz != null && clazz.isInstance(msg)) {

            byte[] bytes = jsonSerializer.serialize(msg);

            byteBuf.writeInt(bytes.length);

            byteBuf.writeBytes(bytes);
        }}
}
